package com.centriole.service.workflow.controller;

import com.centriole.service.workflow.entity.Function;
import com.centriole.service.workflow.entity.Process;
import com.centriole.service.workflow.service.FunctionService;
import com.centriole.service.workflow.service.ProcessService;
import com.centriole.service.workflow.util.AjaxResult;
import com.centriole.service.workflow.util.CommonUtil;
import com.centriole.service.workflow.util.ResultJson;
import com.github.pagehelper.PageInfo;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/flow/function")
public class FunctionController {
	@Resource
    FunctionService functionService;
	@Resource
    ProcessService processService;
	
	@RequestMapping("/list")
	public String toCreateFlow(){
		return "flowpages/functionList";
	};
	
	/**
     * 提供json格式数据
     *
     * @param sortName  排序属性
     * @param sortOrder 排序类型 {asc, desc}
     * @param currPage  当前页
     * @param pageSize  页大小
     * @param request   request
     */
    @ResponseBody
    @RequestMapping("/list/json")
    public ResultJson listJson(@RequestParam(value = "sortname", required = false, defaultValue = "") String sortName,
                           @RequestParam(value = "sortorder", required = false, defaultValue = "") String sortOrder,
                           @RequestParam(value = "page", required = false, defaultValue = "") String currPage,
                           @RequestParam(value = "pagesize", required = false, defaultValue = "") String pageSize,
                           HttpServletRequest request) {

    	Map<String,Object> map = new HashMap<String,Object>();
        try {

        	List<Function> list = functionService.findAll();
        	//查询 方法对应的流程名
        	for(Function fun : list){
                Process process = processService.selectByKey(fun.getProcessId());
                if(process == null) continue;
                fun.setProcessName(process.getProcessName());
            }
         //   list.forEach(e-> System.err.println("流程名: " + e.getProcessName() + " ,  流程Key: " + e.getProcessId()));
            return ResultJson.usePageInfo(new PageInfo<>(list));
        } catch (Exception e) {
            e.printStackTrace();
            return ResultJson.error(ResultJson.INNER_ERR_MSG);
        }
    }
	 /**
     * 方法编辑页面
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/edit")
    public String edit(Model model, HttpServletRequest request, HttpServletResponse response, String id){
		if(CommonUtil.isNotEmpty(id)){
            Function function = functionService.selectById(id);
            Process process = processService.selectByKey(function.getProcessId());
            if(process == null) process = new Process();
            function.setProcessName(process.getProcessName());
     //       System.err.println("目标流程名: " + function.getProcessName());
            model.addAttribute("process", JSONObject.fromObject(function));
		}else{
			model.addAttribute("process", JSONObject.fromObject(new Process()));
		}
   //     System.out.println("----------------------------------------------");
		//主要展示流程的key和流程名字
        List<Process> list = processService.select("");
//		list.forEach(e-> System.err.println("流程名: " + e.getProcessName() + " ,  流程Key: " + e.getProcessKey()));
        model.addAttribute("processList",JSONArray.fromObject(list));
        return "flowpages/functionEdit";
    }
    
    /**
     * 新增方法
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public AjaxResult save(Function function, HttpServletRequest request) {
        try {
        	functionService.insertOrEdit(function);
            return AjaxResult.Success("保存成功", function.getPk());
        } catch (Exception e) {
            return AjaxResult.Error(e.getMessage());
        }
    }
    
    /**
     * 删除方法
     * @param ids
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public Object delete(@RequestParam(value = "ids", required = false, defaultValue = "") String[] ids, HttpServletRequest request) {
        try {
        	for (String id : ids) {
        		functionService.logicDelete(id);
			}
            return AjaxResult.Success("删除成功");
        } catch (Exception ce) {
            return AjaxResult.Error(ce.getMessage());
        }
    }
    
    @ResponseBody
    @RequestMapping(value = "/getComboBoxData")
    public Object getComboBoxData(HttpServletRequest request) {
        String processId = request.getParameter("processId");
        Process process = processService.selectById(processId);
        try {
            //调用Service
            List<Function> list = functionService.selectByProcessKey(process.getProcessKey());
            return list;
        } catch (Exception e) {
//            BapLogUtils.logError(e.getMsg(), e);
        }
        return "SYS.ERROR";
    }

    @ResponseBody
    @RequestMapping(value = "/getFunctionById")
    public Object getFunctionById(HttpServletRequest request) {
        String functionId = request.getParameter("functionId");
        Map<String,String> map = new HashMap<String,String>();
        Function function = functionService.selectById(functionId);
        map.put("functionName", function.getFunctionName());
        return map;
    }
}
